﻿Public Class xtf_LISTADOdeudasTotales
    Public dts_informe As New dts_informe_1
    Public PERMISOImprimir As String = ""


#Region "Total registros ..."

    Private Sub gdv_general_RowCountChanged(ByVal sender As Object, ByVal e As System.EventArgs)
        bsi_registros.Caption = "Total Registros: " & gdv_general.RowCount
    End Sub

#End Region

#Region "General"
    Private Sub bbi_cerrar_ItemClick(ByVal sender As System.Object, ByVal e As DevExpress.XtraBars.ItemClickEventArgs) Handles bbi_cerrar.ItemClick
        Me.Close()
    End Sub

    Private Sub btn_Cerrar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btn_Cerrar.Click
        Me.Close()
    End Sub

    Private Sub bbi_actualizar_ItemClick(ByVal sender As System.Object, ByVal e As DevExpress.XtraBars.ItemClickEventArgs) Handles bbi_actualizar.ItemClick
        IniciarLista()
    End Sub

    Private Sub xtf_Listado_FormClosed(ByVal sender As Object, ByVal e As System.Windows.Forms.FormClosedEventArgs) Handles Me.FormClosed
        guardar_config_usuariocolumna_()
    End Sub

    Private Sub guardar_config_usuariocolumna_()
        Dim obj_config_usuariocolumna_ As New cls_config_usuariocolumna_
        If obj_config_usuariocolumna_.Buscarxidusuarioxmodulo(UsuarioLOG.idusuario, Me.Name) Then
            obj_config_usuariocolumna_.xml = GetLayoutData(gdv_general)
            obj_config_usuariocolumna_.Modificar()
        Else
            obj_config_usuariocolumna_.xml = GetLayoutData(gdv_general)
            obj_config_usuariocolumna_.idusuario = UsuarioLOG.idusuario
            obj_config_usuariocolumna_.modulo = Me.Name
            obj_config_usuariocolumna_.Nuevo()
        End If
    End Sub

    Public Sub FiltrarColumnas()
        Dim int_IDUsuario As Integer = UsuarioLOG.idusuario
        Dim obj_config_usuariocolumna_ As New cls_config_usuariocolumna_
        gdv_general.BeginUpdate()
        If obj_config_usuariocolumna_.Buscarxidusuarioxmodulo(int_IDUsuario, Me.Name) Then
            SetLayoutData(gdv_general, obj_config_usuariocolumna_.xml)
        End If

        PerzonalizarControl(gdc_general)

        gdv_general.EndUpdate()
    End Sub

    Private Function GetLayoutData(ByRef prm_GridView As DevExpress.XtraGrid.Views.Grid.GridView) As Byte()
        Dim stream As New System.IO.MemoryStream()
        prm_GridView.SaveLayoutToStream(stream)
        Return stream.GetBuffer()
    End Function

    Private Sub SetLayoutData(ByRef prm_GridView As DevExpress.XtraGrid.Views.Grid.GridView, ByVal data As Byte())
        If data Is Nothing OrElse data.Length = 0 Then
            Return
        End If
        Dim stream As New System.IO.MemoryStream(data)
        Try
            prm_GridView.RestoreLayoutFromStream(stream)
        Catch ex As Exception
            Throw New Exception("Wrong data format", ex)
        End Try
    End Sub

    Private Sub bbi_columnas_ItemClick(ByVal sender As System.Object, ByVal e As DevExpress.XtraBars.ItemClickEventArgs) Handles bbi_columnas.ItemClick
        gdv_general.ColumnsCustomization()
    End Sub
#End Region

    Public Sub New()

        Me.Cursor = Cursors.WaitCursor
        InitializeComponent()
        PERMISOImprimir = "015004002"
        lbl_modulo.Text = "Deudas Totales Clientes & Proveedores"
        Me.Text = lbl_modulo.Text
        lbl_modulodescripcion.Text = "(detallado por días de la semana)"

        IniciarLista()
        Me.Cursor = Cursors.Default

        cargarTercero_()


    End Sub

    Private Sub cargarTercero_()
        Dim col_ As New Collections.Generic.List(Of CustomListItem2)

        Dim elemento As New CustomListItem2
        elemento.text = "TODOS"
        elemento.var_pkey = 0
        col_.Add(elemento)

        Dim cliente_ As New cls_cliente_
        If cliente_.CargarTodos(True) Then
            For Each cliente As cls_cliente_ In cliente_.Items
                Dim item As New CustomListItem2
                item.objeto = cliente
                item.text = cliente.ToString
                item.var_pkey = cliente.tercero.idtercero
                col_.Add(item)
            Next
        End If

        Dim proveedor_ As New cls_proveedor_
        If proveedor_.CargarTodos(True) Then
            For Each proveedor As cls_proveedor_ In proveedor_.Items
                Dim item As New CustomListItem2
                item.objeto = proveedor
                item.text = proveedor.ToString
                item.var_pkey = proveedor.tercero.idtercero
                col_.Add(item)
            Next
        End If


    End Sub

    Public Sub IniciarLista()
        Try
            gdc_general.BeginUpdate()

            gdc_general.DataSource = dts_informe.Tables("tercero__saldo")

            gdv_general.PopulateColumns()

            gdv_general.Columns("cliente").Caption = "Cliente"
            gdv_general.Columns("saldocliente").Caption = "Saldo"
            gdv_general.Columns("saldocliente").AppearanceCell.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Far
            gdv_general.Columns("saldocliente").AppearanceHeader.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Far
            
            gdv_general.Columns("proveedor").Caption = "Proveedor"
            gdv_general.Columns("saldoproveedor").Caption = "Saldo"
            gdv_general.Columns("saldoproveedor").AppearanceCell.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Far
            gdv_general.Columns("saldoproveedor").AppearanceHeader.TextOptions.HAlignment = DevExpress.Utils.HorzAlignment.Far

            gdc_general.EndUpdate()
            FiltrarColumnas()

            gdv_general.Columns("saldocliente").Summary.Clear()
            gdv_general.Columns("saldocliente").Summary.Add(DevExpress.Data.SummaryItemType.Sum, "saldocliente", "Total: {0}")
            gdv_general.Columns("saldoproveedor").Summary.Clear()
            gdv_general.Columns("saldoproveedor").Summary.Add(DevExpress.Data.SummaryItemType.Sum, "saldoproveedor", "Total: {0}")

            btn_buscar_Click(Nothing, Nothing)
        Catch ex As Exception
            'Dim frmError As New frm_ErrorManager(ex.Message)
        End Try
    End Sub


    Public Sub btn_buscar_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)

        dts_informe.Tables("tercero__saldo").Clear()

        gdv_general.BeginDataUpdate()

        Dim proveedor_ As New cls_proveedor_
        If proveedor_.CargarTodos(False) Then
            For Each proveedor As cls_proveedor_ In proveedor_.Items
                Dim row As DataRow = dts_informe.Tables("tercero__saldo").NewRow
                row("proveedor") = proveedor.ToString
                row("saldoproveedor") = proveedor.tercero.saldoAsiento_
                dts_informe.Tables("tercero__saldo").Rows.Add(row)
            Next
        End If
        Dim cliente_ As New cls_cliente_
        If cliente_.CargarTodos(False) Then
            While dts_informe.Tables("tercero__saldo").Rows.Count - 1 < cliente_.Items.Count
                Dim row As DataRow = dts_informe.Tables("tercero__saldo").NewRow
                dts_informe.Tables("tercero__saldo").Rows.Add(row)
            End While
            For i As Integer = 0 To cliente_.Items.Count - 1
                dts_informe.Tables("tercero__saldo").Rows(i)("cliente") = cliente_.Items(i).ToString
                dts_informe.Tables("tercero__saldo").Rows(i)("saldocliente") = cliente_.Items(i).tercero.saldoAsiento_
            Next
        End If
        gdv_general.EndDataUpdate()

        'gdv_general.Columns("domingo").Caption = "Domingo " & Format(DateAdd(DateInterval.Day, 6, dte_lunes.Date), "dd/MM/yy") & ""


        'Return report
    End Sub

    Public Sub bbi_imprimir_ItemClick(ByVal sender As System.Object, ByVal e As DevExpress.XtraBars.ItemClickEventArgs) Handles bbi_imprimir.ItemClick
        If ComprobarPermiso(PERMISOImprimir) Then
            Dim report As xtf_REPORTEdeudasTotales = generarReporte()
            Try
                report.Print()
            Catch ex As Exception
                ErrManagerShow("Error inesperado.", ex.Message, xtf_ErrManagerAlerta.errManagerImg.img_Error, xtf_ErrManagerAlerta.errManagerBtn.btn_SalirDelSistema)
            End Try
        End If
    End Sub

    Public Sub bbi_exportarPDF_ItemClick(ByVal sender As System.Object, ByVal e As DevExpress.XtraBars.ItemClickEventArgs) Handles bbi_exportarPDF.ItemClick
        If ComprobarPermiso(PERMISOImprimir) Then
            Dim report As xtf_REPORTEdeudasTotales = generarReporte()

            Dim SAVEFILE As New SaveFileDialog
            SAVEFILE.Filter = "PDF (*.PDF)|*.PDF"
            SAVEFILE.FilterIndex = 2
            If SAVEFILE.ShowDialog() = DialogResult.OK Then
                report.ExportToPdf(SAVEFILE.FileName)
            End If
        End If
    End Sub

    Public Sub bbi_vistaprevia_ItemClick(ByVal sender As System.Object, ByVal e As DevExpress.XtraBars.ItemClickEventArgs) Handles bbi_vistaprevia.ItemClick
        If ComprobarPermiso(PERMISOImprimir) Then
            Dim report As xtf_REPORTEdeudasTotales = generarReporte()
            report.ShowPreview()
        End If
    End Sub

    Public Sub bbi_exportarExcel_ItemClick(ByVal sender As System.Object, ByVal e As DevExpress.XtraBars.ItemClickEventArgs) Handles bbi_exportarExcel.ItemClick
        If ComprobarPermiso(PERMISOImprimir) Then
            Dim report As xtf_REPORTEdeudasTotales = generarReporte()
            Dim SAVEFILE As New SaveFileDialog
            SAVEFILE.Filter = "XLS (*.XLS)|*.XLS"
            SAVEFILE.FilterIndex = 2
            If SAVEFILE.ShowDialog() = DialogResult.OK Then
                report.ExportToXls(SAVEFILE.FileName)
            End If
        End If
    End Sub

    Private Sub btn_exportarImprimir_Click(ByVal sender As System.Object, ByVal e As System.EventArgs)
        bbi_vistaprevia_ItemClick(Nothing, Nothing)
    End Sub

    Private Function generarReporte() As xtf_REPORTEdeudasTotales
        Dim report As New xtf_REPORTEdeudasTotales
        report.DataSource = dts_informe


        'report.lbl_titulo.Text = "Cliente: " & cbo_tercero.Text
        report.lbl_subtitulo.Text = "Fecha " & Now.ToShortDateString

        Return report
    End Function
End Class